package cn.demo.admin.controller.sys;

import cn.demo.common.constant.CommonConstants;
import cn.demo.common.core.domain.MapR;
import cn.demo.common.core.domain.R;
import cn.demo.common.core.domain.entity.SysMenu;
import cn.demo.common.core.domain.model.LoginBody;
import cn.demo.common.core.domain.model.LoginUser;
import cn.demo.common.utils.SecurityUtils;
import cn.demo.framework.web.service.SysLoginService;
import cn.demo.framework.web.service.SysPermissionService;
import cn.demo.framework.web.service.TokenService;
import cn.demo.sys.service.ISysMenuService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@RestController
public class SysLoginController {
    @Resource
    private SysLoginService loginService;

    @Resource
    private ISysMenuService menuService;

    @Resource
    private SysPermissionService permissionService;

    @Resource
    private TokenService tokenService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public MapR login(@RequestBody LoginBody loginBody) {
        MapR<Object> ajax = MapR.ok();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(CommonConstants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/getInfo")
    public MapR getInfo() {

        // 登录用户
        LoginUser loginUser = SecurityUtils.getLoginUser();

        // 重新查询
        LoginUser user = loginService.getLoginUser(loginUser.getUsername());
        MapR<Object> ajax = MapR.ok();
        ajax.put("user", user.getUserInfo());
        ajax.put("roles", user.getRoleKeys());
        ajax.put("permissions", user.getPermissions());
        // 刷新缓存
        loginUser.syncBy(user);
        tokenService.refreshToken(loginUser);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("/getRouters")
    public R getRouters() {
        String userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return R.ok(menuService.buildMenus(menus));
    }
}
